package com.liuche.book.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.liuche.framework.common.constant.CommonRedisKey;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @author：liuche
 * @Date：2024年06月30日 18:48
 * @Description：自定义权限验证接口扩展
 */
@Service
@Slf4j
public class StpInterfaceImpl implements StpInterface {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ObjectMapper objectMapper;

    /**
     * 获取用户权限信息
     * @param loginId
     * @param loginType
     * @return
     */
    @SneakyThrows
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 得到用户持有的角色信息
        List<String> roleList = this.getRoleList(loginId, loginType);
        if (CollUtil.isEmpty(roleList)) {
            return Collections.emptyList();
        }
        // 得到角色持有的权限信息
        List<String> list = roleList.stream().map(CommonRedisKey::buildRolePermissionsKey).toList();
        List<String> permissionList = stringRedisTemplate.opsForValue().multiGet(list);

        // 遍历解析
        if (!CollUtil.isEmpty(permissionList)) {
            List<String> res = Lists.newArrayList();

            for (String permissionStr : permissionList) {
                try {
                    List<String> perList= objectMapper.readValue(permissionStr, new TypeReference<>() {});
                    res.addAll(perList);
                } catch (JsonProcessingException e) {
                    log.error("==> JSON 解析错误：", e);
                }
            }
            return res;
        }
        return null;
    }

    /**
     * 获取用户角色信息
     * @param loginId
     * @param loginType
     * @return
     */
    @SneakyThrows
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 构建用户权限 key
        String roleKey = CommonRedisKey.buildUserRoleKey(Long.parseLong(loginId.toString()));
        String roles = stringRedisTemplate.opsForValue().get(roleKey);
        if (null == roles) {
            return Collections.emptyList();
        }
        return objectMapper.readValue(roles, new TypeReference<>() {});
    }
}
